#include "../main.h"

#define PATH_FIFO "/home/yujiu/fifo"

int main()
{
    int res=0;
    res=access(PATH_FIFO,F_OK);
    if(res==-1){
        perror("access");
        exit(EXIT_FAILURE);
    }
    int fd=open(PATH_FIFO,O_RDONLY);
    if(-1==fd){
        perror("open");
        exit(EXIT_FAILURE);
    }
    char buf[128];
    ssize_t byte =0;
    int fds=epoll_create(1);

    struct epoll_event ev[2];
    ev[0].events=EPOLLIN;
    ev[0].data.fd=fd;
    ev[1].events=EPOLLIN;
    ev[1].data.fd=0;

    epoll_ctl(fds,EPOLL_CTL_ADD,fd,ev);
    epoll_ctl(fds,EPOLL_CTL_ADD,0,ev+1);

    struct epoll_event evs[1024];
    int size=sizeof(evs)/sizeof(struct epoll_event);

    while(1){
        res=epoll_wait(fds,evs,size,3000);
        if(res==-1){
            perror("pool");
            close(fd);
            exit(EXIT_FAILURE);
        }else if(0==res){
            printf("timeout\n");
        }else{
            for(int i=0;i<res;i++){
                if(evs[i].data.fd==fd){
                    memset(buf,0,sizeof(buf));
                    byte=read(fd,buf,sizeof(buf));
                    printf("read:%s\n",buf);
                    if(strncmp(buf,"exit",4)==0){
                        close(fd);
                        exit(EXIT_SUCCESS);
                    }
                }
                if(evs[i].data.fd==0){
                    memset(buf,0,sizeof(buf));
                    fgets(buf,sizeof(buf),stdin);
                    buf[strlen(buf)-1]='\0';
                    printf("read:%s\n",buf);
                    if(strncmp(buf,"exit",4)==0){
                        close(fd);
                        exit(EXIT_SUCCESS);
                    }
                }
            }

        }
    }
    close(fd);
    return 0;
}

